package cn.swh.guguanjia.service.impl;

import cn.swh.guguanjia.entity.SysArea;
import cn.swh.guguanjia.entity.SysAreaListener;
import cn.swh.guguanjia.mapper.SysAreaMapper;
import cn.swh.guguanjia.service.SysAreaService;
import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class SysAreaServicelmpl extends BaseServicelmpl<SysArea, Long> implements SysAreaService {


    @Autowired
    SysAreaMapper workOrderMapper;


    @Override
    public PageInfo<SysArea> selectPage(int pageNum, int pageSize, Map<String, Object> condition) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysArea> examines = workOrderMapper.selectPage(condition);
        PageInfo<SysArea> pageInfo = new PageInfo<>(examines);
        return pageInfo;
    }

    @Override
    public int updateByPrimaryKeySelective(Map<String, Object> map) throws JsonProcessingException {
        int result=0;
        if (map.containsKey("area") && !StringUtils.isEmpty(map.get("area"))) {
            ObjectMapper objectMapper = new ObjectMapper();
            String string = objectMapper.writeValueAsString(map.get("area"));
//            SysArea area= (SysArea) map.get("area");
            SysArea area = objectMapper.readValue(string, SysArea.class);

            area.setUpdateDate(new Date());
            result+=super.updateByPrimaryKeySelective(area);

            if(map.containsKey("oldParentIds")&& !StringUtils.isEmpty(map.get("oldParentIds"))){
                String oldParentIds = (String) map.get("oldParentIds");//旧父区域ids
                String parentIds = area.getParentIds();
                if(!oldParentIds.equals(parentIds)){
                    result+= workOrderMapper.updateByParentIds(parentIds, oldParentIds, area.getId());
                }
            }
        }
        return result;
    }

    //文件上传
    @Override
    public void upload(InputStream is){
        EasyExcel.read(is,SysArea.class,new SysAreaListener(workOrderMapper))
                .sheet().doRead();
    }

    //文件下载
    @Override
    public void download(OutputStream os){
        SysArea sysArea = new SysArea();
        sysArea.setDelFlag("0");
        EasyExcel.write(os,SysArea.class).sheet("区域管理").doWrite(workOrderMapper.select(sysArea));
    }


}
